package com.markerhub.modules.app.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.dto.RegisterDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.AppBlueLabel;
import com.markerhub.entity.AppUserSetting;
import com.markerhub.modules.app.LoginData;
import com.markerhub.service.AppBlueLabelService;
import com.markerhub.service.AppUserService;
import com.markerhub.utlis.JwtUtils;
import com.markerhub.utlis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/app")
public class LoginController {

    @Resource
    AppUserService appUserService;


    @Resource
    AppBlueLabelService appBlueLabelService;


    @Resource
    JwtUtils jwtUtils;


    @Resource
    Producer producer;

    @Resource
    RedisUtil redisUtil;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto) {
        // 校验用户名密码
        AppUserSetting appUser = appUserService.login(loginDto);
        // 生成token
        String token = jwtUtils.generateToken(appUser.getId(), "APP");
        LoginData loginData=new LoginData();
        loginData.setToken(token);
        loginData.setUsername(appUser.getUsername());
        loginData.setTell(appUser.getTel());
        loginData.setIdCard(appUser.getIdcard());
        loginData.setLocations(appUser.getLocations());
        loginData.setAreas(appUser.getArea());
        loginData.setUserId(String.valueOf(appUser.getId()));
        loginData.setLeader(String.valueOf(Integer.valueOf(appUser.getLeader())));
        boolean isLogin = isLoginUser(String.valueOf(appUser.getId()));
        log.info("islogin islogin--->"+isLogin);
        if (isLogin==false){
            //进行注册
            List<AppBlueLabel> list = appBlueLabelService.list();
            int k=1;
            for (AppBlueLabel item:list){
                if (item.getId()>=1&&item.getId()<=16){

                    AppBlueLabel appBlueLabel=new AppBlueLabel();
                    k=k+1;

                    appBlueLabel.setLabelKey(item.getLabelKey());
                    appBlueLabel.setUserId(appUser.getId().toString());

                    appBlueLabel.setLabelContent(item.getLabelContent());
                    appBlueLabel.setLabelTime(LocalDateTime.now());
                    appBlueLabel.setIsDelete(item.getIsDelete());
                    appBlueLabel.setUsername(appUser.getUsername());
                    appBlueLabelService.insert(appBlueLabel);
                    //loginList.add(item);
                }
            }
        }
        return Result.success(loginData);
    }

    private boolean isLoginUser(String userId){
        boolean islogin=false;
        List<AppBlueLabel> list = appBlueLabelService.list();
        if (list!=null&&list.size()>0){
            for (int m=0;m<list.size();m++){
                if (String.valueOf(list.get(m).getUserId()).equals(userId)){
                    islogin =true;
                }
            }
        }
        return islogin;

    }
    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        //生成uid和验证码
        String uuid = UUID.randomUUID().toString();
        String code = producer.createText();

        log.info("uuid code {} {}",uuid,code);
        //生成base64编码的图形验证码
        BufferedImage image = producer.createImage(code);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String base64Img = "data:image/jpeg;base64," + encoder.encode(outputStream.toByteArray());

        //把uuid和验证码存储到redis里面
        // 把uuid和验证码存储到redis 默认时间是s 秒
        redisUtil.set(uuid, code, 120);


        //返回uuid和base64图片验证码


        return Result.success(MapUtil.builder()
                .put("uuid", uuid)
                .put("base64Img", base64Img).build());


    }


    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDto form) {



        //判断用户名是否已存在
        long countUserName = appUserService.count(new QueryWrapper<AppUserSetting>().eq("username", form.getUsername()));


        if (countUserName>0){
            return Result.fail("用户名已存在");
        }
        long countTel = appUserService.count(new QueryWrapper<AppUserSetting>().eq("tel", form.getTel()));
        if (countUserName>0 && countTel>0){
            return Result.fail("用户的电话已存在");
        }


        // 进行注册
        AppUserSetting user = new AppUserSetting();
        user.setUsername(form.getUsername());
        user.setTel(form.getTel());
        user.setIdcard(form.getIdcard());
        user.setLocations(form.getLocations());
        user.setArea(form.getAreas());
        user.setLeader((byte) 0);
        appUserService.save(user);





        return Result.success("success");

    }
}
